//
//  WBHomeViewController.swift
//  新浪微博
//
//  Created by 郭鹏飞 on 2016/11/16.
//  Copyright © 2016年 郭鹏飞. All rights reserved.
//

import UIKit

//定义全局常量,尽量使用 private 修饰
private let cellId = "cellId"

class WBHomeViewController: WBBaseController {
    
    //列表视图模型
    lazy var listViewModel = WBStatusListViewModel()
    
    ///微博数据数组
    lazy var statusList = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
     
    }

//MARK: - 加载数据
    override func loadData() {
        
        //print("未加载前的最后一条数据\(self.listViewModel.statusList.last?.text)")
        //刷新表格
        listViewModel.loadStatus (self.isPullup){ (isSuccess,hasMorePullup) in

            //结束刷新
            self.refreshControl?.endRefreshing()
            //回复上拉刷新标记
            self.isPullup = false
            
            //刷新表格
            if hasMorePullup{
                self.tableView?.reloadData()
            }   
        }
    }
    
    ///显示好友
    func showFriends() -> () {
        
        let vc = WBDemoViewController()
        navigationController?.pushViewController(vc, animated: true)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

//MARK: - 表格数据源方法
extension WBHomeViewController{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        
        cell.textLabel?.text = listViewModel.statusList[indexPath.row].text
        
        return cell
        
    }
}

//MARK: - 设置界面
extension WBHomeViewController{
    
    //重写父类extension的方法 不可以写父类本类的方法
    override func setupTableView(){
        super.setupTableView()
        
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        
        //注册原型 cell
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        
        setupNavTitle()
    }
    
    private func setupNavTitle() {
    
        let title = WBNetworkManager.shared.userAccount.screen_name
        
        let button = WBTitleButton(title: title)
        
        button.addTarget(self, action: #selector(clickTitleBtn), for: .touchUpInside)
        
        navItem.titleView = button
    }
    
    @objc func clickTitleBtn(btn: UIButton){
        //设置选中状态
        btn.isSelected = !btn.isSelected
    }
}

